//加权数组
const mul = [ 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2 ];
//值Z对应的校验码
const code = [ 49,48,88,57,56,55,54,53,52,51,50 ];

//校验身份证
function checkIdCard(idCard) {
    // 不合规身份证
	if (typeof(idCard)!='string' && idCard.length != 18)
        return false;
	// 校验码
	let z = 0;
	for (let j = 0; j < 17; j++)
	{
		//身份证号前几位有非数字的说明是不合规的
		if (idCard.charCodeAt(j) < 48 || idCard.charCodeAt(j)> 57)
			return false;

		//对前十七位进行加权
		z += (idCard.charCodeAt(j) - 48) * mul[j];
	}

	if ('x' === idCard.charAt(17))
    {
        idCard = idCard.substring(0, 17);
        idCard += 'X';
    }

	//与校验码比对
	return (code[z % 11] == idCard.charCodeAt(17));
}

//提取身份证里的生日
function getBirthday(idCard) {
    return idCard.substring(6, 14);
}

//年龄
function getAge(iBirthday) {
    if (iBirthday <= 0)
        return false;
    let d = new Date();
    let now = d.getFullYear()*10000+(d.getMonth()+1)*100+d.getDate();
    return (now - iBirthday) / 10000;
}

//校验生日数字是否成年
function checkAdultByBirthdayInt(iBirthday) {
	return getAge(iBirthday) >= 18; // 满18
}

//校验生日字符串是否成年
function checkAdultByBirthday(strBirthday) {
    // 非法生日
	if (typeof(strBirthday)!='string' && strBirthday.length != 8)
        return false;
    let birthday = parseInt(strBirthday);
    return checkAdultByBirthdayInt(birthday);
}


module.exports.checkIdCard = checkIdCard;
module.exports.getBirthday = getBirthday;
module.exports.checkAdultByBirthday = checkAdultByBirthday;
